package com.ruoyi.jihuo.config;

import com.ruoyi.jihuo.service.impl.JhTmUploadDataServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池监控配置
 */
@Configuration
@EnableScheduling
public class ThreadPoolMonitorConfig {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolMonitorConfig.class);

    @Autowired
    @Qualifier("uploadDataAnalysisExecutor")
    private ThreadPoolTaskExecutor uploadDataAnalysisExecutor;

    /**
     * 每60秒监控一次线程池状态
     */
    @Scheduled(fixedRate = 60000)
    private void monitorThreadPoolStatus() {
        // 获取当前活跃线程数
        int activeCount = uploadDataAnalysisExecutor.getActiveCount();
        // 获取核心线程数
        int corePoolSize = uploadDataAnalysisExecutor.getCorePoolSize();
        // 获取最大线程数
        int maxPoolSize = uploadDataAnalysisExecutor.getMaxPoolSize();
        // 获取队列中等待的任务数
        int queueSize = uploadDataAnalysisExecutor.getQueueSize();

        // 获取底层的 ThreadPoolExecutor 对象
        ThreadPoolExecutor threadPoolExecutor = uploadDataAnalysisExecutor.getThreadPoolExecutor();
        // 获取已完成的任务数
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        // 获取总任务数
        long taskCount = threadPoolExecutor.getTaskCount();

        log.info("线程池[uploadDataAnalysisExecutor]状态: 活跃线程数={}, 核心线程数={}, 最大线程数={}, 等待任务数={}, 已完成任务数={}, 总任务数={}",
                activeCount, corePoolSize, maxPoolSize, queueSize, completedTaskCount, taskCount);
    }
}